package com.ifast.oupei.util;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.FileTemplateResolver;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.itextpdf.text.pdf.BaseFont;

public class PDFParserUtil {
	
	/**
	 * 返回pdf文件
	 * @param docs：document数组
	 * @return
	 * @throws Exception
	 */
	public static File getPdfOutputStream(List<Document> docs)  throws Exception{
		String name = "temp"+(int)(Math.random()*1000)+".pdf";
	    File file = new File(name);
		OutputStream out = new FileOutputStream(file);
	    ITextRenderer renderer = new ITextRenderer();
	    ITextFontResolver fontResolver = renderer.getFontResolver();
		fontResolver.addFont("C:/Windows/Fonts/msyhbd.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		fontResolver.addFont("C:/Windows/Fonts/msyh.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		renderer.setDocument(docs.get(0), null);
        renderer.layout();
        renderer.createPDF(out,false);
        //添加多页pdf
        if(docs.size()>1){
	        for (int i = 1; i < docs.size(); i++) {
	        	renderer.setDocument(docs.get(i),null);;
	            renderer.layout();
	            renderer.writeNextDocument();
			}
        }
        renderer.finishPDF();
		return file;
	}
	/**
	 * 解析模板文件，生成html文本的documen
	 * @param filePath：解析的html所在路径
	 * @param template：模板名字
	 * @param variables：模板文件当中所含有的参数
	 * @return
	 * @throws Exception
	 */
	public static Document generate(String filePath, String template, Map<String, Object> variables) throws Exception {
		// 创建模板解析器
		FileTemplateResolver templateResolver = new FileTemplateResolver();
		templateResolver.setPrefix(filePath);
		templateResolver.setSuffix(".html");
		templateResolver.setCharacterEncoding("UTF-8");
		templateResolver.setTemplateMode("XHTML");
		templateResolver.setCacheTTLMs(Long.valueOf(3600000L));
		templateResolver.setCacheable(true);
		// 创建模板引擎并初始化解析器
		TemplateEngine engine = new TemplateEngine();
		engine.setTemplateResolver(templateResolver);
		// engine.initialize();

		// 输出流
		StringWriter stringWriter = new StringWriter();
		BufferedWriter writer = new BufferedWriter(stringWriter);

		// 获取上下文
		Context ctx = new Context();
		ctx.setVariables(variables);
		engine.process(template, ctx, writer);

		stringWriter.flush();
		stringWriter.close();
		writer.flush();
		writer.close();

		// 输出html
		String htmlStr = stringWriter.toString();
		DocumentBuilder builder =  DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc = builder.parse(new ByteArrayInputStream(htmlStr.getBytes("UTF-8")));
		return doc;
	}
}
